package com.rui.sideup.module.io;

/**
 * @author ZhangRui
 * @date 2023/05/15 16:52
 **/

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

@Service
@Slf4j
public class OrderServiceImpl {

    public void createOrder() {
        //1、同步处理核心业务逻辑
        log.info("同步处理业务逻辑");
        //2、通过线程池提交，异步处理非核心逻辑，例如日志埋点
        AsyncManager.service.execute(() -> {
            System.out.println("线程->" + Thread.currentThread().getName() + ",正在执行异步日志处理任务");
        });
        // return CreateOrderBO.builder().result(true).build();
    }

    public void createOrder2() {
        //Future异步处理返回执行结果
        //定义接收线程执行结果的FutureTask对象
        List<Future<Integer>> results = Collections.synchronizedList(new ArrayList<>());
        //实现Callable接口定义线程执行逻辑
        results.add(AsyncManager.service.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int a = 1, b = 2;
                System.out.println("Callable接口执行中");
                return a + b;
            }
        }));

        //输出线程返回结果
        for (Future<Integer> future : results) {
            try {
                //这里获取结果，等待时间设置200毫秒
                System.out.println("a+b=" + future.get(200, TimeUnit.MILLISECONDS));
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
        //判断线程是否执行完毕，完毕则获取执行结果
        // return CreateOrderBO.builder().result(true).build();
    }
}